<template>
  <div class="common-page">
    <div class="common-page-content">
      <el-card class="common-card">
        <!-- 搜索和操作区域 -->

        <div class="search-section">
          <ul class="search-form">
            <li class="form_item">
              <el-input v-model="searchForm.title" placeholder="公告标题" style="width: 200px" clearable />
            </li>
            <li class="form_item">
              <el-button type="primary" @click="handleSearch" class="search-btn">
                搜索
              </el-button>
            </li>
            <li class="form_item">
              <el-button type="primary" @click="handleAdd" class="add-btn">
                新增公告
              </el-button>
            </li>
          </ul>
        </div>

        <!-- 表格区域 -->
        <div class="common-table-container">
          <table class="common-table">
            <thead>
              <tr>
                <th style="width: 80px;">序号</th>
                <th style="min-width: 200px;">公告标题</th>
                <th style="width: 180px;">创建时间</th>
                <th style="width: 200px;">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="row in tableData" :key="row.id">
                <td>{{ row.id }}</td>
                <td>{{ row.title }}</td>
                <td>{{ row.addtime }}</td>
                <td>
                  <el-button size="small" :icon="View" @click="handleView(row)" class="action-btn" title="查看" circle />
                  <el-button size="small" :icon="Edit" @click="handleEdit(row)" class="action-btn" title="编辑" circle />
                  <el-button size="small" :icon="Delete" @click="handleDelete(row)" class="action-btn" title="删除"
                    circle />
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页区域 -->
        <div class="common-pagination-section">
          <el-pagination :current-page="pagination.currentPage" :page-size="pagination.pageSize" :small="true"
            :background="true" layout="total, prev, pager, next, jumper" :total="pagination.total" pager-count="5"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" class="common-pagination" />
          <button class="tg_btm" @size-change="handleSizeChange">跳转</button>

        </div>
      </el-card>
    </div>

    <!-- 添加/编辑弹框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" :close-on-click-modal="false"
      :close-on-press-escape="false" class="notice-dialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="notice-form">
        <!-- 公告标题 -->
        <el-form-item label="公告标题" prop="title" class="form-item">
          <el-input v-model="form.title" placeholder="请输入公告标题" style="width: 100%" />
        </el-form-item>

        <!-- 所属部门 -->
        <el-form-item label="所属部门" prop="did" class="form-item">
          <el-select v-model="form.did" filterable placeholder="请选择所属部门" style="width: 100%" clearable>
            <el-option v-for="dept in departmentOptions" :key="dept.id" :label="dept.dpname" :value="dept.id">
              <span v-html="dept.html" style="letter-spacing:6px"></span>
              {{ dept.dpname }}
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 内容 -->
        <el-form-item label="内容" prop="content" class="form-item content-item">
          <WangEditor v-model="form.content" :height="400" placeholder="请输入公告内容" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="submitLoading" class="confirm-btn">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看弹框 -->
    <el-dialog v-model="viewDialogVisible" title="查看公告" width="800px" class="view-dialog">
      <div class="view-content">
        <div class="view-title">{{ viewData.title }}</div>
        <div class="view-meta">
          <span>所属部门：{{ getDepartmentName(viewData.did) }}</span>
        </div>
        <div class="view-html" v-html="viewData.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View, Edit, Delete } from '@element-plus/icons-vue'
import WangEditor from '@/components/common/WangEditor.vue'
import { getNoticeList, addNotice, editNotice, deleteNotice } from '@/api/setting'
import { useUserStore } from '@/stores/user'
import TOOLS from '@/utils/tools'

// 响应式数据
const searchForm = reactive({
  title: ''
})

// 表格数据
const tableData = ref([])

// 分页数据 - 参考department/Index.vue的实现
const pagination = reactive({
  currentPage: 1,    // 当前页码
  pageSize: 30,      // 每页显示条数
  total: 0           // 总条数
})

// 表格加载状态
const tableLoading = ref(false)

// 获取用户store和部门选项
const userStore = useUserStore()
const departmentOptions = ref([])

// 初始化部门选项
const initDepartmentOptions = () => {
  try {


    if (!userStore.init_option || !userStore.init_option.common_option) {
      console.warn('用户store中没有初始化选项，使用空数组')
      departmentOptions.value = []
      return
    }

    const departOption = userStore.init_option.common_option.depart_option || []

    // 使用tools.js的Flaten方法处理部门数据
    if (Array.isArray(departOption) && departOption.length > 0) {
      departmentOptions.value = TOOLS.Flaten(departOption)
    } else {
      departmentOptions.value = []
    }

  } catch (error) {
    console.error('初始化部门选项失败:', error)
    departmentOptions.value = []
  }
}

// 弹框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentEditId = ref(null)

const form = reactive({
  id: '',
  title: '',
  did: '',
  content: ''
})

const rules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' }
  ],
  did: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ]
}

const formRef = ref()
const submitLoading = ref(false)

// 查看弹框
const viewDialogVisible = ref(false)
const viewData = reactive({
  title: '',
  did: '',
  content: '',
  addtime: ''
})

// 初始化
onMounted(async () => {

  try {
    // 先初始化部门选项
    initDepartmentOptions()

    // 延迟加载公告列表，避免阻塞页面渲染
    setTimeout(async () => {
      try {
        await loadNoticeList()
      } catch (error) {
        console.error('加载公告列表失败:', error)
        ElMessage.error('加载公告列表失败')
      }
    }, 100)

  } catch (error) {
    console.error('页面初始化失败:', error)
    ElMessage.error('页面初始化失败')
  }
})

// ==================== 数据加载方法 ====================

/**
 * 加载公告列表 - 参考department/Index.vue的loadStaffList方法
 */
const loadNoticeList = async () => {
  try {
    // 开启表格加载状态
    tableLoading.value = true

    // 构建搜索条件（POST数据）
    const searchData = {
      title: searchForm.title
    }

    // 获取当前分页参数（GET参数）
    const page = pagination.currentPage


    // 调用API获取公告列表数据
    const response = await getNoticeList(searchData, page)

    // 检查API响应状态并更新数据
    if (response.status) {
      // 更新公告列表数据
      tableData.value = response.data.list || []
      // 更新分页总数
      pagination.total = Number(response.data.count) || 0
    } else {
      // API返回失败状态，清空数据
      tableData.value = []
      pagination.total = 0
      ElMessage.error(response.msg || '获取公告列表失败')
    }
  } catch (error) {
    // 捕获异常并显示错误提示
    console.error('加载公告列表失败:', error)
    ElMessage.error('加载公告列表失败')
    // 清空数据避免显示错误信息
    tableData.value = []
    pagination.total = 0
  } finally {
    // 无论成功失败都要关闭加载状态
    tableLoading.value = false
  }
}



// ==================== 搜索相关方法 ====================

/**
 * 处理搜索
 */
const handleSearch = async () => {
  // 重置到第一页
  pagination.currentPage = 1
  await loadNoticeList()
}

// 添加公告
const handleAdd = () => {
  dialogTitle.value = '新增公告'
  isEdit.value = false
  currentEditId.value = null
  resetForm()

  // 设置默认部门为第一个部门
  if (departmentOptions.value && departmentOptions.value.length > 0) {
    form.did = departmentOptions.value[0].id
  }

  dialogVisible.value = true
}

// 编辑公告
const handleEdit = (row) => {
  dialogTitle.value = '编辑公告'
  isEdit.value = true
  currentEditId.value = row.id
  form.id = row.id
  form.title = row.title
  form.did = row.did
  form.content = row.content
  dialogVisible.value = true
}

// 查看公告
const handleView = (row) => {
  viewData.title = row.title
  viewData.did = row.did
  viewData.content = row.content
  viewData.create_time = row.create_time
  viewDialogVisible.value = true
}

/**
 * 处理删除公告
 */
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除公告"${row.title}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteNotice(row.id)

    if (response.status) {
      ElMessage.success('删除公告成功')
      // 重新加载公告列表
      await loadNoticeList()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除公告失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// ==================== 分页相关方法 ====================

// 创建分页处理器
const paginationHandlers = TOOLS.createPaginationHandlers(
  pagination,
  null, // 这个页面没有 form.page_size
  () => loadNoticeList(),
  { scrollToTopOnPageChange: true }
)

// 使用公共分页处理方法
const { handleSizeChange, handleCurrentChange } = paginationHandlers

// ==================== 表单处理方法 ====================

/**
 * 重置表单
 */
const resetForm = () => {
  Object.assign(form, {
    id: '',
    title: '',
    did: '',
    content: ''
  })

  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

/**
 * 处理表单提交
 */
const handleConfirm = async () => {
  if (!formRef.value) return

  try {
    // 表单验证
    await formRef.value.validate()
    submitLoading.value = true

    // 准备提交数据
    const submitData = {
      did: form.did,
      title: form.title,
      content: form.content
    }

    // 如果是编辑模式，添加ID
    if (isEdit.value) {
      submitData.id = form.id
    }

    // 调用对应的API
    const apiMethod = isEdit.value ? editNotice : addNotice
    const response = await apiMethod(submitData)

    if (response.status) {
      ElMessage.success(isEdit.value ? '编辑公告成功' : '新增公告成功')
      dialogVisible.value = false
      resetForm()
      // 重新加载公告列表
      await loadNoticeList()
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'validation failed') {
      console.error('提交公告失败:', error)
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// ==================== 辅助方法 ====================

/**
 * 获取部门名称
 */
const getDepartmentName = (did) => {
  if (!did) return '未知部门'

  const department = departmentOptions.value.find(dept => dept.id == did)
  return department ? department.dpname : '未知部门'
}
</script>

<style scoped>
/* 弹框样式 */
.notice-dialog :deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid var(--theme-border-base);
}

.notice-dialog :deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: var(--theme-text-primary);
}

.notice-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.notice-form {
  max-width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-item :deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--theme-text-regular);
}

.content-item {
  margin-bottom: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 20px 0;
  border-top: 1px solid var(--theme-border-base);
}

.cancel-btn {
  background: var(--theme-bg-primary);
  border-color: var(--theme-border-base);
  color: var(--theme-text-regular);
}

.cancel-btn:hover {
  background: var(--theme-bg-secondary);
  border-color: var(--theme-border-dark);
  color: var(--theme-primary);
}

.confirm-btn {
  background: var(--theme-primary);
  border-color: var(--theme-primary);
}

.confirm-btn:hover {
  background: var(--theme-primary-dark);
  border-color: var(--theme-primary-dark);
}

/* 查看弹框样式 */
.view-dialog :deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid var(--theme-border-base);
}

.view-content {
  padding: 20px;
}

.view-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--theme-text-primary);
  margin-bottom: 15px;
}

.view-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--theme-border-base);
  color: var(--theme-text-secondary);
  font-size: 14px;
}

.view-html {
  line-height: 1.6;
  color: var(--theme-text-regular);
  max-height: 300px;
  overflow-y: auto;
}

.view-html :deep(p) {
  margin-bottom: 10px;
}

.view-html :deep(img) {
  max-width: 100%;
  height: auto;
}

/* 操作按钮样式 */
.action-btn {
  margin-right: 8px;
  width: 32px;
  height: 32px;
  padding: 0;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.action-btn:last-child {
  margin-right: 0;
}

.action-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 查看按钮 */
.action-btn.el-button--primary {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  border-color: #409eff;
  color: white;
}

.action-btn.el-button--primary:hover {
  background: linear-gradient(135deg, #66b1ff, #409eff);
  border-color: #66b1ff;
}

/* 编辑按钮 */
.action-btn.el-button--warning {
  background: linear-gradient(135deg, #e6a23c, #f0a020);
  border-color: #e6a23c;
  color: white;
}

.action-btn.el-button--warning:hover {
  background: linear-gradient(135deg, #f0a020, #e6a23c);
  border-color: #f0a020;
}

/* 删除按钮 */
.action-btn.el-button--danger {
  background: linear-gradient(135deg, #f56c6c, #f78989);
  border-color: #f56c6c;
  color: white;
}

.action-btn.el-button--danger:hover {
  background: linear-gradient(135deg, #f78989, #f56c6c);
  border-color: #f78989;
}
</style>
